package com.dbkj.axb_conf;

import com.alibaba.fastjson.JSON;
import com.dbkj.axb.AxbService;
import com.dbkj.common.model.AxbConf;
import com.jfinal.aop.Before;
import com.jfinal.aop.Inject;
import com.jfinal.core.Controller;
import com.jfinal.ext.interceptor.Restful;
import com.jfinal.json.Json;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.render.JsonRender;

import java.util.List;

/**
 * @Author: Max
 * @Date: 2019/10/30 14:51
 */


public class AxbConfController extends Controller {

    @Inject
    AxbConfService service;
    @Inject
    AxbService axbService;

    /**
     * 分页展示
     */
    @Before(Restful.class)
    public void index(){
        Integer pageNumber = getParaToInt("pageNumber");
        Integer pageSize = getParaToInt("pageSize");
        String openid = getPara("openid");
        Page<AxbConf> page = service.paginate(pageNumber,pageSize,openid);
        renderJson(Ret.ok().set("total",page.getTotalRow()).set("rows", JSON.toJSON(page.getList())));
    }

    public void list(){
        List list = service.list();
        renderJson(Ret.ok().set("rows",list));
    }

    @Before(Restful.class)
    public void delete(){
        Integer id = getParaToInt();
        if(axbService.hasConf(id)){
            renderError(401,new JsonRender(Ret.by("msg","有相关联的x号码")));
        }else {
            service.delete(id);
            renderJson(Ret.ok());
        }
    }

    @Before(Restful.class)
    public void update(){
        Json.getJson().parse(getRawData(),AxbConf.class).update();
        renderJson(Ret.ok());
    }

    @Before(Restful.class)
    public void save(){
        AxbConf conf = Json.getJson().parse(getRawData(),AxbConf.class);
        String openid = conf.getOpenid();
        boolean flag = service.exist(openid);
        if(flag){
            renderError(409, new JsonRender(Ret.by("msg","openid已经存在")));
            return;
        }else {
            conf.save();
            renderJson(Ret.ok());
        }
    }

}
